﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Components
{
    public class ButtonLoading : Button
    {     /// <summary>
          /// 获得/设置 按钮点击后的回调方法
          /// </summary>
        [Parameter]
        public Func<Task>? OnClickCallback { get; set; }

        [Parameter]
        public string LoadingText { set; get; } = "";


        /// <summary>
        /// OnInitialized 方法
        /// </summary>
        protected override void OnInitialized()
        {
            LoadingIcon = "fa fa-spinner fa-spin fa-fw";
            base.OnInitialized();

            var onClick = OnClick;
            OnClick = EventCallback.Factory.Create<MouseEventArgs>(this, async e =>
            {
                string text = this.Text;
                string icon = this.Icon;
                if (!IsDisabled)
                {
                    this.Icon = this.LoadingIcon;
                    if (!string.IsNullOrWhiteSpace(this.LoadingText))
                    {
                        this.Text = this.LoadingText;
                    }
                    this.SetDisable(true);
                    await InvokeAsync(StateHasChanged);
                    if (onClick.HasDelegate) await onClick.InvokeAsync(e);

                    if (OnClickCallback != null) await OnClickCallback.Invoke();
                    if (OnClickWithoutRender != null) await OnClickWithoutRender.Invoke();
                    this.Icon = icon;
                    this.Text = text;
                    this.SetDisable(false);
                }
            });
        }
    }
}
